#include "uiloader.h"
#include "abstractcontainer.h"
#include "abstractstorage.h"
#include "workbench.h"
#include "scriptmanager.h"
#include "defines.h"
#include "scriptfunctions.h"

#include <QFile>
#include <QDebug>
#include <QVariant>
#include <QWidget>

# define SSIGNAL(a)   "2"+a.toLatin1()

UiLoader::UiLoader(QObject *parent) :
    QUiLoader(parent)
{
}

QWidget* UiLoader::createWidget(const QString &className, QWidget *parent,const QString &name)
{
    QWidget *widget = QUiLoader::createWidget(className, parent, name);
    if(parent == 0 && m_mainWidget == 0) {
        m_scriptWidget = ScriptManager::instance()->engine()->newQObject(widget);
        m_mainWidget = widget;
    } else if( m_mainWidget != 0 ) {
        QScriptValue widgetproperty = ScriptManager::instance()->engine()->newQObject(widget);
        m_scriptWidget.setProperty(name, widgetproperty);
        extraProperties(name, className);
    }

    if (m_connections != 0) {
        for(int i = 0; i < m_connections->size(); i++) {
            AbstractStorage* con = m_connections->at(i);
            //signal and slots
            if (name.compare(con->property(XML_SENDER).toString()) == 0 ) {
                //connect signal with function in script
                QScriptValue global = ScriptManager::instance()->engine()->globalObject();
                QScriptValue handler = global.property(con->property(XML_SLOT).toString().replace(QRegExp("\\(.*\\)"), ""));
                qScriptConnect(widget, SSIGNAL(con->property(XML_SIGNAL).toString()), global, handler);
            }
        }
    }
    return widget;
}

QWidget* UiLoader::load(QString str, AbstractContainer *cons)
{
    m_mainWidget = 0;
    m_connections = cons;
    QFile uiFile(str);
    uiFile.open(QIODevice::ReadOnly);
    QWidget *wgt = QUiLoader::load(&uiFile);//1000 createWidget
    ScriptManager::instance()->engine()->globalObject().setProperty(m_mainWidget->objectName(),m_scriptWidget);
    return wgt;
}

QWidget* UiLoader::load(QIODevice* d, QWidget* parent)
{
    m_mainWidget = 0;
    m_connections = 0;
    return QUiLoader::load(d,parent);
}

void UiLoader::extraProperties(const QString &scriptValue, const QString &className)
{
    if( (className.compare("QTableWidget") == 0)
            || (className.compare("QTableView") == 0)
            || (className.compare("QTreeWidget") == 0)
            || (className.compare("QTreeView") == 0) ) {
        QScriptValue func = ScriptManager::instance()->engine()->newFunction(searchDialogTableView);
        m_scriptWidget.property(scriptValue).setProperty("searchDialog", func);
    }
}
